package study.alex.resumedb.gae.backend;

import com.google.appengine.api.LifecycleManager;
import com.google.appengine.api.ThreadManager;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;

/**
 * Created with IntelliJ IDEA.
 * Author: Alexey Kuznetsov
 * Date: 14.03.14
 * Time: 14:54
 * SVN $Id$
 */
public class ResumeDbTasksServlet extends HttpServlet {
    private static final Logger log = Logger.getLogger(ResumeDbTasksServlet.class.getName());

    @Override
    protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
        log.fine("Task request: " + req.getRequestURI() + " Query: " + req.getQueryString());
        final study.alex.resumedb.gae.backend.BackendWorker worker = new study.alex.resumedb.gae.backend.DefaultBackendWorker();

        LifecycleManager.getInstance().setShutdownHook(new LifecycleManager.ShutdownHook() {
            @Override
            public void shutdown() {
                worker.shutdown();
            }
        });

        Thread thread = ThreadManager.createBackgroundThread(new Runnable() {
            @Override
            public void run() {
                worker.handleRequest(req);
            }
        });

        if (thread != null) {
            thread.start();
            resp.setStatus(HttpServletResponse.SC_OK);
        } else {
            log.severe("Can't create worker thread");
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
